<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import PaginationCommon from '@/components/PaginationCommon.vue'
import DepartmentService from '@/api/services/DepartmentService'
import UserService from '@/api/services/UserService'

// 部门数据类型定义
interface Department {
  id: number
  departmentName: string
  departmentDesc: string
  status: 1 | 0 // 状态：0-禁用，1-启用
  parentId: number
  minister: number
  createTime: string
  updateTime: string
}

// 响应数据
const departmentList = ref<Department[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const currentDepartmentId = ref<number | null>(null)
const selectedDepartments = ref<number[]>([])

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 下拉框数据
const departmentOptions = ref<{ id: number; departmentName: string }[]>([])
const userOptions = ref<{ id: number; realname: string }[]>([])

// 表单数据
const form = reactive({
  id: 0,
  departmentName: '',
  departmentDesc: '',
  status: 1 as 1 | 0,
  parentId: 0,
  minister: 0
})

// 表单引用
const formRef = ref<FormInstance>()

// 表单验证规则
const rules = reactive<FormRules>({
  departmentName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '部门名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  departmentDesc: [
    { max: 100, message: '部门描述不能超过 100 个字符', trigger: 'blur' }
  ]
})

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
]

// 获取部门下拉框数据
const fetchDepartmentOptions = async () => {
  try {
    // 在编辑时排除当前部门自身，避免选择自己作为上级部门
    const excludeId = isEdit.value ? currentDepartmentId.value : 0
    const result = await DepartmentService.getDepartmentDropdownBoxAsync(excludeId || 0)
    if (result.success) {
      departmentOptions.value = [
        { id: 0, departmentName: '无' },
        ...(result.data as { id: number; departmentName: string }[])
      ]
    } else {
      ElMessage.error(`获取部门下拉框失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取部门下拉框失败:', error)
    ElMessage.error('获取部门下拉框失败')
  }
}

// 获取用户下拉框数据
const fetchUserOptions = async () => {
  try {
    const result = await UserService.getUserDropdownBoxAsync()
    if (result.success) {
      userOptions.value = [
        { id: 0, realname: '无' },
        ...(result.data as { id: number; realname: string }[])
      ]
    } else {
      ElMessage.error(`获取用户下拉框失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取用户下拉框失败:', error)
    ElMessage.error('获取用户下拉框失败')
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  loading.value = true
  try {
    // 调用DepartmentService的getDepartmentPagedListAsync方法
    const result = await DepartmentService.getDepartmentPagedListAsync({
      departmentName: searchForm.departmentName,
      status: searchForm.status,
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    })

    if (result.success) {
      // 更新部门列表和分页数据 - 使用类型断言将unknown[]转换为Department[]
      departmentList.value = result.data.data as Department[]
      total.value = result.data.totalCount
      currentPage.value = result.data.pageIndex
      pageSize.value = result.data.pageSize
    } else {
      ElMessage.error(`获取部门列表失败: ${result.message}`)
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  } finally {
    loading.value = false
  }
}

// 分页变化处理
const handlePageChange = (page: number, size: number) => {
  currentPage.value = page
  pageSize.value = size
  fetchDepartments()
}

// 打开添加部门对话框
const openAddDialog = async () => {
  dialogTitle.value = '添加部门'
  isEdit.value = false
  currentDepartmentId.value = null

  // 重置表单
  Object.assign(form, {
    id: 0,
    departmentName: '',
    departmentDesc: '',
    status: 1,
    parentId: 0,
    minister: 0
  })

  // 获取下拉框数据
  await Promise.all([
    fetchDepartmentOptions(),
    fetchUserOptions()
  ])

  dialogVisible.value = true
}

// 打开编辑部门对话框
const openEditDialog = async (department: Department) => {
  dialogTitle.value = '编辑部门'
  isEdit.value = true
  currentDepartmentId.value = department.id

  // 先获取下拉框数据，确保currentDepartmentId已经设置
  await Promise.all([
    fetchDepartmentOptions(),
    fetchUserOptions()
  ])

  // 填充表单数据（在下拉框数据获取完成后）
  Object.assign(form, {
    id: department.id,
    departmentName: department.departmentName,
    departmentDesc: department.departmentDesc,
    status: department.status,
    parentId: department.parentId,
    minister: department.minister
  })

  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value && form.id) {
          // 更新部门
          const updateParams = {
            id: form.id,
            departmentName: form.departmentName,
            departmentDesc: form.departmentDesc,
            status: form.status,
            parentId: form.parentId,
            minister: form.minister
          }
          const result = await DepartmentService.updateDepartmentAsync(updateParams)

          if (result.success) {
            ElMessage.success('部门更新成功')
            dialogVisible.value = false
            fetchDepartments() // 刷新列表
          } else {
            ElMessage.error(`更新部门失败: ${result.message}`)
          }
        } else {
          // 添加部门
          const addParams = {
            departmentName: form.departmentName,
            departmentDesc: form.departmentDesc
          }
          const result = await DepartmentService.addDepartmentAsync(addParams)

          if (result.success) {
            ElMessage.success('部门添加成功')
            dialogVisible.value = false
            fetchDepartments() // 刷新列表
          } else {
            ElMessage.error(`添加部门失败: ${result.message}`)
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(isEdit.value ? '更新部门失败' : '添加部门失败')
      }
    }
  })
}

// 切换部门状态
const toggleStatus = async (department: Department) => {
  try {
    const newStatus = department.status === 1 ? 0 : 1
    const action = newStatus === 1 ? '启用' : '禁用'

    await ElMessageBox.confirm(
      `确定要${action}部门 "${department.departmentName}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用DepartmentService的单个部门状态更新方法
    const result = await DepartmentService.updateDepartmentStatusAsync(department.id)

    if (result.success) {
      // 更新本地数据状态
      const index = departmentList.value.findIndex(d => d.id === department.id)
      if (index !== -1) {
        departmentList.value[index]!.status = newStatus
        departmentList.value[index]!.updateTime = new Date().toLocaleString('zh-CN')
      }
      ElMessage.success(`部门${action}成功`)
    } else {
      ElMessage.error(`部门${action}失败: ${result.message}`)
    }
  } catch {
    // 用户取消操作
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

// 搜索相关数据
const searchForm = reactive({
  departmentName: '',
  status: 1 as 1 | 0 | ''
})

// 搜索部门
const searchDepartments = () => {
  // 重置到第一页进行搜索
  currentPage.value = 1
  fetchDepartments()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    departmentName: '',
    status: 1
  })
  fetchDepartments()
}

// 批量启用部门
const batchEnableDepartments = async () => {
  if (selectedDepartments.value.length === 0) {
    ElMessage.warning('请选择要启用的部门')
    return
  }

  try {
    const selectedNames = departmentList.value
      .filter(department => selectedDepartments.value.includes(department.id))
      .map(department => department.departmentName)
      .join('、')

    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedDepartments.value.length} 个部门吗？\n${selectedNames}`,
      '批量启用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用DepartmentService的批量状态更新方法
    const result = await DepartmentService.updateDepartmentsStatusAsync(selectedDepartments.value)

    if (result.success) {
      // 更新本地数据状态
      selectedDepartments.value.forEach(departmentId => {
        const department = departmentList.value.find(d => d.id === departmentId)
        if (department) {
          department.status = 1
          department.updateTime = new Date().toLocaleString('zh-CN')
        }
      })
      ElMessage.success('批量启用成功')
      selectedDepartments.value = []
    } else {
      ElMessage.error(`批量启用失败: ${result.message}`)
    }
  } catch {
    // 用户取消操作
  }
}

// 批量禁用部门
const batchDisableDepartments = async () => {
  if (selectedDepartments.value.length === 0) {
    ElMessage.warning('请选择要禁用的部门')
    return
  }

  try {
    const selectedNames = departmentList.value
      .filter(department => selectedDepartments.value.includes(department.id))
      .map(department => department.departmentName)
      .join('、')

    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedDepartments.value.length} 个部门吗？\n${selectedNames}`,
      '批量禁用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用DepartmentService的批量状态更新方法
    const result = await DepartmentService.updateDepartmentsStatusAsync(selectedDepartments.value)

    if (result.success) {
      // 更新本地数据状态
      selectedDepartments.value.forEach(departmentId => {
        const department = departmentList.value.find(d => d.id === departmentId)
        if (department) {
          department.status = 0
          department.updateTime = new Date().toLocaleString('zh-CN')
        }
      })
      ElMessage.success('批量禁用成功')
      selectedDepartments.value = []
    } else {
      ElMessage.error(`批量禁用失败: ${result.message}`)
    }
  } catch {
    // 用户取消操作
  }
}

// 时间转换
const formatDate = (dateString: string | number | Date) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toISOString().split('T')[0]; // 格式：YYYY-MM-DD
}

// 页面加载时获取部门列表
onMounted(() => {
  fetchDepartments()
})
</script>

<template>
  <div class="department-container">

    <!-- 搜索栏 - 单行布局 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-form :model="searchForm" label-width="auto" class="search-form">
          <div class="search-row">
            <el-form-item label="部门名称">
              <el-input v-model="searchForm.departmentName" placeholder="部门名称" clearable style="width: 140px" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 120px">
                <el-option label="全部" value="" />
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
            <div class="search-actions">
              <el-button type="primary" @click="searchDepartments" size="small">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch" size="small">
                <el-icon>
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </div>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 部门列表 -->
    <div class="table-container">
      <el-card class="content-card">
        <template #header>
          <div class="table-header">
            <span>部门列表</span>
            <div class="header-actions">
              <el-button type="primary" @click="openAddDialog">
                <el-icon>
                  <Plus />
                </el-icon>
                添加部门
              </el-button>
              <el-button type="success" @click="batchEnableDepartments" :disabled="selectedDepartments.length === 0">
                批量启用
              </el-button>
              <el-button type="warning" @click="batchDisableDepartments" :disabled="selectedDepartments.length === 0">
                批量禁用
              </el-button>
              <el-button @click="fetchDepartments">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <div class="table-wrapper">
          <el-table :data="departmentList" v-loading="loading" style="width: 100%" stripe
            @selection-change="(selection: Department[]) => selectedDepartments = selection.map(department => department.id)">
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column prop="id" label="ID" width="80" fixed="left" />
            <el-table-column prop="departmentName" label="部门名称" min-width="150" />
            <el-table-column prop="departmentDesc" label="部门描述" min-width="200" />
            <el-table-column prop="parentId" label="上级部门ID" width="120" />
            <el-table-column prop="minister" label="负责人" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180"
              :formatter="(row: { createTime: any }) => formatDate(row.createTime)" />
            <el-table-column prop="updateTime" label="更新时间" width="180"
              :formatter="(row: { updateTime: any }) => formatDate(row.updateTime)" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="openEditDialog(row)">
                  编辑
                </el-button>
                <el-button size="small" :type="row.status === 1 ? 'warning' : 'success'" @click="toggleStatus(row)">
                  {{ row.status === 1 ? '禁用' : '启用' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <!-- 分页组件 - 固定在底部 -->
      <div class="pagination-container">
        <PaginationCommon v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          @page-change="handlePageChange" />
      </div>
    </div>

    <!-- 添加/编辑部门对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入部门名称" />
        </el-form-item>

        <el-form-item label="部门描述" prop="departmentDesc">
          <el-input v-model="form.departmentDesc" type="textarea" placeholder="请输入部门描述" :rows="3" />
        </el-form-item>

        <el-form-item v-if="isEdit" label="上级部门">
          <el-select v-model="form.parentId" placeholder="请选择上级部门" style="width: 100%">
            <el-option v-for="item in departmentOptions" :key="item.id" :label="item.departmentName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="isEdit" label="负责人">
          <el-select v-model="form.minister" placeholder="请选择负责人" style="width: 100%">
            <el-option v-for="item in userOptions" :key="item.id" :label="item.realname" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in statusOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.department-container {
  padding: 20px;
  height: calc(100vh - 40px);
  /* 减去padding */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
  margin: 0;
  gap: 8px;
  max-height: calc(100vh - 40px);
}

h1 {
  color: #303133;
  margin-bottom: 16px;
  font-size: 24px;
  font-weight: 600;
}

p {
  color: #606266;
  margin-bottom: 24px;
  font-size: 14px;
}

/* 搜索栏样式 - 单行布局 */
.search-card {
  margin-bottom: 0;
  border-radius: 6px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
  overflow: visible;
  z-index: 20;
  position: relative;
  max-height: 80px;
  min-height: 80px;
  background: #fff;
}

.search-bar {
  padding: 12px 20px;
  position: relative;
  z-index: 15;
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 0;
  height: auto;
}

/* 搜索表单样式 - 单行布局 */
:deep(.search-form) {
  display: flex;
  flex-direction: column;
  gap: 0;
  width: 100%;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
  flex-wrap: nowrap;
  justify-content: space-between;
}

:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
  height: 36px;
  margin-right: 0;
  flex-shrink: 0;
}

:deep(.search-form .el-form-item__label) {
  line-height: 36px;
  padding-bottom: 0;
  font-size: 14px;
  margin-right: 8px;
  width: auto;
  display: flex;
  align-items: center;
  color: #606266;
  font-weight: 500;
  min-width: max-content;
  white-space: nowrap;
}

:deep(.search-form .el-input) {
  height: 36px;
  width: auto;
  flex-shrink: 0;
}

:deep(.search-form .el-input__inner) {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 100%;
  padding: 0 12px;
}

:deep(.search-form .el-select) {
  height: 36px;
  width: auto;
  flex-shrink: 0;
}

:deep(.search-form .el-select .el-input__inner) {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 100%;
  padding: 0 12px;
}

.search-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  height: 36px;
  margin-left: auto;
  flex-shrink: 0;
}

:deep(.search-actions .el-button) {
  height: 36px;
  padding: 0 16px;
  font-size: 14px;
  min-width: 70px;
}

/* 表格容器样式 - 固定高度确保滚动条显示 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  position: relative;
  margin-top: 0;
  height: calc(100vh - 160px);
}

/* 表格包装器样式 - 固定高度和滚动设置 */
.table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: hidden;
  position: relative;
  margin-top: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 表格样式 - 固定高度确保滚动条 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.el-table .el-table__header-wrapper) {
  flex-shrink: 0;
}

:deep(.el-table .el-table__body-wrapper) {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  max-height: 470px;
  /* 固定高度确保滚动条 */
}

/* 确保表格行高度合适 */
:deep(.el-table__row) {
  height: 48px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

/* 分页容器样式 - 固定在底部 */
.pagination-container {
  flex-shrink: 0;
  margin-top: 8px;
  padding: 12px 20px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.08);
  position: sticky;
  bottom: 0;
  z-index: 10;
  max-width: calc(100vw - 40px);
  box-sizing: border-box;
  margin-bottom: 0;
  height: auto;
  min-height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

/* 表格标题样式 - 固定头部 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  background: inherit;
  z-index: 10;
}

/* 卡片内容区域样式 - 自适应高度 */
:deep(.el-card__body) {
  padding: 16px;
  margin-top: 0;
  height: auto;
  min-height: 0;
  overflow: visible;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

:deep(.el-table .el-button) {
  margin-right: 8px;
}

:deep(.el-table .el-button:last-child) {
  margin-right: 0;
}

/* 固定表格头部和操作列 */
:deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 10;
}

:deep(.el-table__fixed-header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 11;
}

:deep(.el-table__fixed-right) {
  position: sticky;
  right: 0;
  z-index: 10;
}

:deep(.el-table__fixed-left) {
  position: sticky;
  left: 0;
  z-index: 10;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 20px 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 10px 20px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 输入框样式 */
:deep(.el-input) {
  border-radius: 6px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
}

/* 卡片标题样式 */
:deep(.el-card__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
  font-weight: 600;
  color: #303133;
  border-radius: 12px 12px 0 0;
  position: sticky;
  top: 0;
  z-index: 10;
}
</style>
